<template>
    <div class="merchant-management-container">
        <div class="header-card">
            <h2>商家管理</h2>
            <p>管理平台商家信息</p>
        </div>

        <el-card class="table-card" shadow="never">
            <div class="toolbar">
                <el-button type="primary" @click="addMerchant" icon="el-icon-plus">新增商家</el-button>
                <div class="search-area">
                    <el-input v-model="searchKeyword" placeholder="搜索商家名称或联系电话" style="width: 300px; margin-left: 20px;"
                        clearable @keyup.enter="fetchData">
                        <template #append>
                            <el-button icon="el-icon-search" @click="fetchData"></el-button>
                        </template>
                    </el-input>
                </div>
            </div>

            <el-table :data="tableData" style="width: 100%" border stripe v-loading="loading">
                <el-table-column prop="id" label="ID" width="80" align="center" />
                <el-table-column prop="shop_name" label="商家名称" min-width="180" />
                <el-table-column label="所在地区" min-width="200">
                    <template #default="scope">{{ getFullLocation(scope.row) }}</template>
                </el-table-column>
                <el-table-column prop="address" label="详细地址" min-width="200" />
                <el-table-column prop="leader_name" label="负责人" width="120" align="center" />
                <el-table-column prop="leader_phone" label="联系电话" width="150" align="center" />
                <el-table-column prop="accout" label="商家账号" min-width="150" />
                <el-table-column prop="create_time" label="创建时间" width="170" align="center">
                    <template #default="scope">{{ formatDate(scope.row.create_time) }}</template>
                </el-table-column>
                <el-table-column label="状态" width="120" align="center">
                    <template #default="scope">
                        <el-tag :type="getStatusType(scope.row.apply_status)" effect="dark">
                            {{ getStatusText(scope.row.apply_status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right" align="center">
                    <template #default="scope">
                        <el-button size="small" type="primary" @click="editMerchant(scope.row)" plain
                            round>编辑</el-button>
                        <el-button size="small" type="danger" @click="deleteMerchant(scope.row)" plain
                            round>删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination-container">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="700px" :before-close="handleDialogClose">
            <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px" label-position="right">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="商家名称:" prop="shop_name">
                            <el-input v-model="formData.shop_name" placeholder="请输入商家名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="负责人:" prop="leader_name">
                            <el-input v-model="formData.leader_name" placeholder="请输入负责人姓名" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="联系电话:" prop="leader_phone">
                            <el-input v-model="formData.leader_phone" placeholder="请输入联系电话" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="身份证号:" prop="leader_idcard">
                            <el-input v-model="formData.leader_idcard" placeholder="请输入负责人身份证号" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 修改为直接显示的输入框 -->
                <el-form-item label="所在地区:" prop="area">
                    <el-input v-model="formData.area" placeholder="请输入所在地区（例如：广东省深圳市南山区）" />
                </el-form-item>

                <el-form-item label="详细地址:" prop="address">
                    <el-input v-model="formData.address" placeholder="请输入详细地址" />
                </el-form-item>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="商家账号:" prop="accout">
                            <el-input v-model="formData.accout" placeholder="请输入商家账号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="密码:" prop="password" v-if="isAddMode">
                            <el-input v-model="formData.password" type="password" placeholder="请输入密码" show-password />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="状态:" prop="apply_status">
                    <el-select v-model="formData.apply_status" placeholder="请选择状态" style="width: 100%">
                        <el-option label="待审核" value="0"></el-option>
                        <el-option label="审核通过" value="1"></el-option>
                        <el-option label="审核失败" value="2"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="营业执照:">
                    <el-upload class="license-uploader" action="http://localhost:8889/api/upload/business" method="post"
                        :show-file-list="false" :on-success="handleLicenseSuccess" :before-upload="beforeLicenseUpload"
                        name="file">
                        <img v-if="formData.image_url" :src="getImageUrl(formData.image_url)"
                            class="license-image-preview" />
                        <el-icon v-else class="license-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleDialogClose">取消</el-button>
                    <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'

const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)
const searchKeyword = ref('')
const formRef = ref(null)
const isAddMode = ref(true)
// 移除 selectedRegion，不再使用级联选择器

const baseUrl = 'http://localhost:8889' // 后端服务地址

// 移除 regionOptions 和 regionProps，不再使用级联选择器

const formData = reactive({
    id: '',
    shop_name: '',
    province: '', // 保留但不直接使用
    city: '',     // 保留但不直接使用
    area: '',     // 主要使用这个字段
    address: '',
    leader_name: '',
    leader_phone: '',
    leader_idcard: '',
    accout: '',
    password: '',
    image_url: '',
    apply_status: '0'
})

// 移除 validateRegion 自定义校验函数

const formRules = {
    shop_name: [
        { required: true, message: '请输入商家名称', trigger: 'blur' }
    ],
    leader_name: [
        { required: true, message: '请输入负责人姓名', trigger: 'blur' }
    ],
    leader_phone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$|^0\d{2,3}-?\d{7,8}$/, message: '请输入正确的电话号码', trigger: 'blur' }
    ],
    leader_idcard: [
        { required: true, message: '请输入负责人身份证号', trigger: 'blur' },
        { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
    ],
    address: [
        { required: true, message: '请输入详细地址', trigger: 'blur' }
    ],
    area: [
        { required: true, message: '请输入所在地区', trigger: 'blur' }
    ],
    accout: [
        { required: true, message: '请输入商家账号', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
    ],
    apply_status: [
        { required: true, message: '请选择状态', trigger: 'change' }
    ]
}

const dialogTitle = computed(() => {
    return isAddMode.value ? '新增商家' : '编辑商家'
})

// 移除 handleRegionChange 函数，不再需要监听级联选择器变化

// 解析图片URL
const parseImageUrl = (imageUrl) => {
    if (!imageUrl) return ''
    try {
        const urls = JSON.parse(imageUrl)
        return Array.isArray(urls) && urls.length > 0 ? urls[0] : ''
    } catch (e) {
        return imageUrl
    }
}

// 获取图片完整URL
const getImageUrl = (url) => {
    const parsedUrl = parseImageUrl(url)
    if (!parsedUrl) return ''
    if (parsedUrl.startsWith('http')) return parsedUrl
    return `${baseUrl}${parsedUrl}`
}

const fetchData = async () => {
    loading.value = true
    try {
        const response = await axios.get(`${baseUrl}/api/admin/business/list`, {
            params: {
                page: currentPage.value,
                pageSize: pageSize.value,
                shop_name: searchKeyword.value,
                leader_phone: searchKeyword.value
            }
        })

        if (response.data.code === 200) {
            tableData.value = response.data.data
            total.value = response.data.pagination.total
        } else {
            ElMessage.error(response.data.message || '获取商家列表失败')
        }
    } catch (error) {
        ElMessage.error('获取商家列表失败: ' + error.message)
    } finally {
        loading.value = false
    }
}

const getFullLocation = (row) => {
    if (!row) return ''
    // 根据实际返回的数据结构调整
    if (row.area && row.area.includes('省') && row.area.includes('市')) {
        return row.area
    }
    return `${row.province || ''}${row.city || ''}${row.area || ''}`
}

const formatDate = (date) => {
    if (!date) return ''
    return date.replace('T', ' ').substring(0, 19)
}

const getStatusText = (status) => {
    const statusMap = { '0': '待审核', '1': '审核通过', '2': '审核失败' }
    return statusMap[status] || '未知状态'
}

const getStatusType = (status) => {
    const typeMap = { '0': 'warning', '1': 'success', '2': 'danger' }
    return typeMap[status] || 'info'
}

const addMerchant = () => {
    isAddMode.value = true
    resetForm()
    dialogVisible.value = true
}

const editMerchant = (row) => {
    isAddMode.value = false
    Object.assign(formData, row)

    // 特别处理图片URL
    if (row.image_url) {
        formData.image_url = parseImageUrl(row.image_url)
    }

    dialogVisible.value = true
}

const deleteMerchant = (row) => {
    ElMessageBox.confirm(
        `确定要删除商家"${row.shop_name}"吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        try {
            const response = await axios.delete(`${baseUrl}/api/admin/business/${row.id}`)
            if (response.data.code === 200) {
                ElMessage.success('删除成功')
                fetchData()
            } else {
                ElMessage.error(response.data.message || '删除失败')
            }
        } catch (error) {
            ElMessage.error('删除失败: ' + error.message)
        }
    }).catch(() => {
        // 用户取消删除
    })
}

const resetForm = () => {
    Object.assign(formData, {
        id: '',
        shop_name: '',
        province: '',
        city: '',
        area: '',
        address: '',
        leader_name: '',
        leader_phone: '',
        leader_idcard: '',
        accout: '',
        password: '',
        image_url: '',
        apply_status: '0'
    })
    // 不再需要重置 selectedRegion
    if (formRef.value) {
        formRef.value.resetFields()
    }
}

const handleDialogClose = (done) => {
    dialogVisible.value = false
    resetForm()
}

const submitForm = () => {
    formRef.value.validate(async (valid) => {
        if (valid) {
            submitLoading.value = true
            try {
                let response
                if (isAddMode.value) {
                    // 新增商家
                    response = await axios.post(`${baseUrl}/api/admin/business/addBusiness`, {
                        shop_name: formData.shop_name,
                        province: formData.province, // 保留但可能为空
                        city: formData.city,         // 保留但可能为空
                        area: formData.area,         // 主要使用这个字段
                        address: formData.address,
                        leader_name: formData.leader_name,
                        leader_phone: formData.leader_phone,
                        leader_idcard: formData.leader_idcard,
                        accout: formData.accout,
                        password: formData.password,
                        image_url: formData.image_url,
                        apply_status: formData.apply_status
                    })
                } else {
                    // 编辑商家
                    const updateData = {
                        shop_name: formData.shop_name,
                        province: formData.province, // 保留但可能为空
                        city: formData.city,         // 保留但可能为空
                        area: formData.area,         // 主要使用这个字段
                        address: formData.address,
                        leader_name: formData.leader_name,
                        leader_phone: formData.leader_phone,
                        leader_idcard: formData.leader_idcard,
                        accout: formData.accout,
                        image_url: formData.image_url,
                        apply_status: formData.apply_status
                    }

                    // 如果编辑时填写了密码，则更新密码
                    if (formData.password) {
                        updateData.password = formData.password
                    }

                    response = await axios.put(`${baseUrl}/api/admin/business/${formData.id}`, updateData)
                }

                if (response.data.code === 200) {
                    ElMessage.success(isAddMode.value ? '新增商家成功' : '编辑商家成功')
                    dialogVisible.value = false
                    fetchData()
                } else {
                    ElMessage.error(response.data.message || (isAddMode.value ? '新增商家失败' : '编辑商家失败'))
                }
            } catch (error) {
                ElMessage.error((isAddMode.value ? '新增商家失败' : '编辑商家失败') + ': ' + error.message)
            } finally {
                submitLoading.value = false
            }
        }
    })
}

const handleLicenseSuccess = (response, uploadFile) => {
    if (response.code === 200) {
        formData.image_url = response.data.business_img_url
        ElMessage.success('营业执照上传成功')
    } else {
        ElMessage.error(response.message || '营业执照上传失败')
    }
}

const beforeLicenseUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('营业执照只能是 JPG 或 PNG 格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 5) {
        ElMessage.error('营业执照大小不能超过 5MB!')
        return false
    }
    return true
}

const handleSizeChange = (val) => {
    pageSize.value = val
    fetchData()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchData()
}

onMounted(() => {
    fetchData()
})
</script>

<style scoped>
.merchant-management-container {
    min-height: calc(100vh - 80px);
}

.header-card {
    background: #409eff;
    color: white;
    padding: 20px 30px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-card h2 {
    margin: 0 0 10px 0;
    font-size: 24px;
    font-weight: 500;
}

.header-card p {
    margin: 0;
    opacity: 0.9;
    font-size: 14px;
}

.table-card {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.toolbar {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    padding: 15px 0;
}

.license-uploader .license-image-preview {
    width: 200px;
    height: 150px;
    display: block;
    border-radius: 6px;
}

.license-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.license-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.license-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 150px;
    text-align: center;
}
</style>